package com.atguigu.common.valid.validator;

import com.atguigu.common.valid.annotation.ListValue;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;

public class ListValueConstraintValidator implements ConstraintValidator<ListValue,Integer> {

    private Set<Integer> set = new HashSet<>();

    /**
     * Initializes the validator in preparation for
     *   初始化方法
     * @param constraintAnnotation annotation instance for a given constraint declaration
     */
    @Override
    public void initialize(ListValue constraintAnnotation) {

        int[] vals = constraintAnnotation.vals();

        if(vals!= null && vals.length >0 ){
            for(int val : vals){
                set.add(val);
            }
        }

    }

    /**
     * @param value   object to validate  需要校验的值
     * @param context context in which the constraint is evaluated 上下文环境信息
     * @return {@code false} if {@code value} does not pass the constraint
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {

        // 判断是否包含值
        return set.contains(value);
    }
}
